package com.alibaba.citrus.cr.sales.plan.facade.service.statistics.stat.scItem;

import com.alibaba.acm.shaded.com.google.common.collect.Sets;
import com.alibaba.citrus.cr.common.annotation.FunctionInvoker;
import com.alibaba.citrus.cr.sales.plan.model.enums.ContractDataSourceEnum;
import com.alibaba.citrus.cr.sales.plan.model.enums.ContractStatDimensionEnum;
import com.alibaba.citrus.cr.sales.plan.model.enums.SalesStatBizTypeEnum;
import com.alibaba.citrus.cr.sales.plan.model.enums.StatPoolTypeEnum;
import com.alibaba.citrus.cr.sales.plan.repository.request.StatScItemQueryRequest;
import com.alibaba.citrus.cr.sales.plan.sdo.SalesPlanSDO;
import com.alibaba.citrus.cr.sales.plan.sdo.SalesPlanStatScItemSDO;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.MonthContractAndRollingCountResponse;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.QueryContractByCustomerDimensionRequest;
import com.alibaba.citrus.cr.sales.plan.facade.service.SalesPlanCommonService;
import com.alibaba.citrus.cr.sales.plan.facade.service.statistics.stat.SalesPlanStatAtomAbstract;
import com.alibaba.citrus.cr.sales.plan.facade.service.statistics.stat.model.SalesPlanStatRequest;
import com.alibaba.cz.base.tool.log.Log;
import com.epoch.app.bcorder.sales_plan.salesplandetail.dto.PlanScItemStatByManageEmployeeCountRequest;
import com.epoch.app.bcorder.sales_plan.salesplandetail.dto.PlanScItemStatByManageEmployeeCountResponse;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.math.BigDecimal;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.stream.Collectors;

/**
 * @author luyi
 * @date 2021/12/2 5:42 下午
 */
public class ScItemEmployeeStatService extends SalesPlanStatAtomAbstract {

    private static final Log log = Log.getLogger(ScItemEmployeeStatService.class);

    public ScItemEmployeeStatService(SalesPlanStatRequest statRequest,CountDownLatch latch){
        super.statRequest = statRequest;
        super.latch = latch;
    }

    @Override
    protected void handle(SalesPlanStatRequest statRequest) {
        statEmployeeScItem(statRequest.getSalesPlan(),statRequest.getYear(),statRequest.getMonth());
    }

    @Override
    protected String taskName() {
        return "statEmployeeScItem";
    }

    /**
     * 货品维度
     * 业务员货品汇总
     *
     * @param salesPlan
     */
    @FunctionInvoker(printLog = true)
    private void statEmployeeScItem(SalesPlanSDO salesPlan, String year, String month) {
        PlanScItemStatByManageEmployeeCountRequest request = new PlanScItemStatByManageEmployeeCountRequest();
        request.setPlanId(salesPlan.getId());
        PlanScItemStatByManageEmployeeCountResponse planScItemStatByManageEmployeeCount = salesPlanDetailService.planScItemStatByManageEmployeeCount(request);
        if (Objects.isNull(planScItemStatByManageEmployeeCount)) {
            log.info("SalesPlanStatServiceImpl_scItemStat_statCount_is_null,statEmployeeScItem");
            return;
        }
        Integer count = planScItemStatByManageEmployeeCount.getCount();
        if (count == null || count <= 0) {
            log.info("SalesPlanStatServiceImpl_scItemStat_statCount_is_null,statEmployeeScItem2");
            return;
        }
        int totalPage = (count + CUSTOMER_ADDRESS_PAGE_SIZE - 1) / CUSTOMER_ADDRESS_PAGE_SIZE;
        log.info("SalesPlanStatServiceImpl_statEmployeeScItem_statCount_size={},totalPage={}",count,totalPage);
        for (int i = 1; i <= totalPage; i++) {
            StatScItemQueryRequest statQueryRequest = new StatScItemQueryRequest();
            statQueryRequest.setPlanId(salesPlan.getId());
            statQueryRequest.setManageEmployee(true);
            statQueryRequest.setPage(i);
            statQueryRequest.setSize(CUSTOMER_ADDRESS_PAGE_SIZE);
            List<SalesPlanStatScItemSDO> salesPlanStatScItemList = salesPlanLineRepository.queryStatPlanScItemList(statQueryRequest);
            if (CollectionUtils.isEmpty(salesPlanStatScItemList)) {
                log.info("SalesPlanStatServiceImpl_scItemStat_queryStatList_is_null,statEmployeeScItem");
                return;
            }
            log.info("SalesPlanStatServiceImpl_statEmployeeScItem_queryStatList_size={}",salesPlanStatScItemList.size());
            //批量查询业务员货品合同量，合同金额
            Set<String> salesManList = new HashSet<>();
            Set<String> scItemIdList = new HashSet<>();
            for (SalesPlanStatScItemSDO salesPlanStatScItem : salesPlanStatScItemList) {
                if(StringUtils.isNotBlank(salesPlanStatScItem.getBizId())) {
                    salesManList.add(salesPlanStatScItem.getBizId());
                }
                scItemIdList.add(salesPlanStatScItem.getScItemId());
            }
            QueryContractByCustomerDimensionRequest queryContractRequest = new QueryContractByCustomerDimensionRequest();
            queryContractRequest.setType(ContractStatDimensionEnum.EMPLOYEE_SC_ITEM.getCode());
            queryContractRequest.setContractYear(year);
            queryContractRequest.setPlanMonth(month);
            queryContractRequest.setManageEmployeeIds(Lists.newArrayList(salesManList));
            queryContractRequest.setScItemIds(Lists.newArrayList(scItemIdList));
            queryContractRequest.setDataSource(ContractDataSourceEnum.CUSTOMER.getCode());
            List<MonthContractAndRollingCountResponse> monthContractList = contractRepository.queryQuantityListByAddressAndScItem(queryContractRequest);
            Map<String, MonthContractAndRollingCountResponse> collect = Maps.newHashMap();
            if (CollectionUtils.isNotEmpty(monthContractList)) {
                collect = monthContractList.stream().collect(Collectors.toMap(m -> SalesPlanCommonService.getCombinationKey(m.getManageEmployeeId(), m.getScItemId()), m -> m));
            }
            for (SalesPlanStatScItemSDO planStatScItem : salesPlanStatScItemList) {
                planStatScItem.setPoolType(StatPoolTypeEnum.SC_ITEM.getPoolType());
                planStatScItem.setBizType(SalesStatBizTypeEnum.SALESMAN.getBizType());
                //需要查合同量补充
                MonthContractAndRollingCountResponse monthContract = collect.get(SalesPlanCommonService.getCombinationKey(planStatScItem.getBizId(), planStatScItem.getScItemId()));
                setStatContractInfo(planStatScItem, monthContract);
                calculateSatisfaction(salesPlan.getStatus(), planStatScItem);

                //20220901  汇总计算单价，，折前计划金额/计划量，两位精度
                BigDecimal costInsuranceFreight = planStatScItem.getMonthCount()==0?new BigDecimal(0):new BigDecimal(planStatScItem.getBeforeMonthMoney()).divide(new BigDecimal(planStatScItem.getMonthCount()),0,BigDecimal.ROUND_HALF_UP);
                planStatScItem.setCostInsuranceFreight(costInsuranceFreight.longValue());
                // 汇总 计算出库价，，折前出库金额/计划量，两位精度
                BigDecimal outboundPrice = planStatScItem.getMonthCount()==0?new BigDecimal(0):new BigDecimal(planStatScItem.getPlanOutboundMoney()).divide(new BigDecimal(planStatScItem.getMonthCount()),0,BigDecimal.ROUND_HALF_UP);
                planStatScItem.setOutboundPrice(outboundPrice.longValue());
            }
            Boolean result = salesPlanScItemStatRepository.batchCreatePlanScItem(salesPlanStatScItemList);
            log.info("SalesPlanStatServiceImpl_statcItem_batchCreatePlanScItem_result={},statEmployeeScItem",result);
        }
    }
}
